package cn.felord.security.autoconfigure.handler;

import cn.felord.security.autoconfigure.SecureUser;
import cn.felord.security.autoconfigure.jwt.JwtTokenGenerator;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * The type Login authentication success handler.
 *
 * @author felord.cn
 * @since 2021 /3/27 11:27
 */
@AllArgsConstructor
public class LoginAuthenticationSuccessHandler extends ResponseWriter implements AuthenticationSuccessHandler {
    private final JwtTokenGenerator jwtTokenGenerator;
    private static final String ATTRIBUTE_KEY = "cn.felord.authentication";


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        request.setAttribute(ATTRIBUTE_KEY, authentication);
        this.write(request, response);
    }

    @Override
    protected Rest<?> body(HttpServletRequest request) {
        Authentication authentication = (Authentication) request.getAttribute(ATTRIBUTE_KEY);

        SecureUser userDetails = (SecureUser) authentication.getPrincipal();
        return RestBody.okData(jwtTokenGenerator.tokenResponse(userDetails));
    }
}
